{% extends 'base.html' %}
{% load static %}

{% block title %}个人中心 - 本地有约{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row">
        <!-- 左侧个人信息 -->
        <div class="col-lg-4 mb-4">
            <div class="card shadow-sm">
                <div class="card-body text-center p-4">
                    <div class="position-relative d-inline-block mb-3">
                        <img src="{{ user.avatar_url|default:'/static/images/default-avatar.jpg' }}"
                             alt="用户头像" class="rounded-circle" width="120" height="120" style="object-fit: cover;">
                        <button class="btn btn-primary btn-sm position-absolute bottom-0 end-0 rounded-circle"
                                style="width: 36px; height: 36px;" data-bs-toggle="modal" data-bs-target="#editAvatarModal">
                            <i class="fas fa-camera"></i>
                        </button>
                    </div>
                    <h4 class="mb-1">{{ user.username }}</h4>
                    <p class="text-muted mb-3">
                        {% if user.user_type == 'organizer' %}
                        <span class="badge bg-warning text-dark">🎯 活动组织者</span>
                        {% endif %}
                        {% if user.show_location and user.location %}{{ user.location }}{% else %}未知地区{% endif %}
                    </p>

                    <!-- 统计信息 -->
                    <div class="d-flex justify-content-center mb-3">
                        <div class="px-3 text-center">
                            <div class="h5 mb-0 text-primary">{{ following_count }}</div>
                            <small class="text-muted">关注</small>
                        </div>
                        <div class="px-3 text-center border-start border-end">
                            <div class="h5 mb-0 text-primary">{{ followers_count }}</div>
                            <small class="text-muted">粉丝</small>
                        </div>
                        <div class="px-3 text-center">
                            <div class="h5 mb-0 text-primary">{{ user.points }}</div>  <!-- 积分 -->
                            <small class="text-muted">积分</small>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="d-grid gap-2">
                        <button class="btn btn-outline-primary w-100" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                            <i class="fas fa-edit me-2"></i>编辑资料
                        </button>
                    </div>

                    <!-- 个人简介和兴趣标签 -->
                    <div class="text-start mt-3">
                        {% if user.bio %}
                        <h6 class="mb-2">个人简介</h6>
                        <p class="text-muted small">{{ user.bio }}</p>
                        {% endif %}

                        {% if user.interests %}
                        <h6 class="mb-2 mt-3">兴趣标签</h6>
                        <div>
                            {% for interest in user.interests.split %}
                            <span class="badge bg-light text-dark me-1 mb-1">{{ interest }}</span>
                            {% endfor %}
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 数据统计 -->
            <div class="card shadow-sm mt-4">
                <div class="card-header bg-light">
                    <h6 class="mb-0">📊 我的数据</h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-4">
                            <div class="h5 text-primary mb-1">{{ events_attended }}</div>
                            <small class="text-muted">参与活动</small>
                        </div>
                        <div class="col-4">
                            <div class="h5 text-primary mb-1">{{ events_organized }}</div>
                            <small class="text-muted">发起活动</small>
                        </div>
                        <div class="col-4">
                            <div class="h5 text-primary mb-1">{{ reviews_count }}</div>
                            <small class="text-muted">发表评价</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="col-lg-8">
            <!-- 功能菜单 -->
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-light">
                    <h6 class="mb-0">📱 功能菜单</h6>
                </div>
                <div class="card-body p-0">
                    <!-- 修改功能菜单部分，移除所有 href 跳转 -->
                    <div class="list-group list-group-flush">
                        <!-- 个人主页 -->
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center active"
                           data-bs-toggle="tab" data-bs-target="#profileContent">
                            <i class="fas fa-home text-primary me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">个人主页</h6>
                                <small class="text-muted">查看个人动态和统计</small>
                            </div>
                        </a>

                        <!-- 我发起的活动 -->
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center"
                           data-bs-toggle="tab" data-bs-target="#myEventsContent">
                            <i class="fas fa-calendar-alt text-primary me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">我发起的活动</h6>
                                <small class="text-muted">查看和管理我创建的活动</small>
                            </div>
                            <span class="badge bg-primary rounded-pill">{{ events_organized }}</span>
                        </a>

                        <!-- 我报名的活动 -->
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center"
                           data-bs-toggle="tab" data-bs-target="#myRegistrationsContent">
                            <i class="fas fa-check-circle text-success me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">我报名的活动</h6>
                                <small class="text-muted">查看我已报名和参与的活动</small>
                            </div>
                            <span class="badge bg-success rounded-pill">{{ events_attended }}</span>
                        </a>

                        <!-- 我的评价 -->
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center"
                           data-bs-toggle="tab" data-bs-target="#myReviewsContent">
                            <i class="fas fa-comment text-info me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">我的评价</h6>
                                <small class="text-muted">查看我发表的所有评论</small>
                            </div>
                            <span class="badge bg-info rounded-pill">{{ reviews_count }}</span>
                        </a>

                        <!-- 积分明细 -->
                       <a href="#" class="list-group-item list-group-item-action d-flex align-items-center"
                           data-bs-toggle="tab" data-bs-target="#pointHistoryContent">
                            <i class="fas fa-coins text-warning me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">积分明细</h6>
                                <small class="text-muted">查看积分获取和消费记录</small>
                            </div>
                            <i class="fas fa-chevron-right text-muted"></i>
                        </a>
                        <!-- 隐私设置 -->
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center"
                           data-bs-toggle="tab" data-bs-target="#privacySettingsContent">
                            <i class="fas fa-cog text-secondary me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">隐私设置</h6>
                                <small class="text-muted">管理个人信息公开设置</small>
                            </div>
                            <i class="fas fa-chevron-right text-muted"></i>
                        </a>

                        <!-- 草稿箱 -->
                        <a href="#" class="list-group-item list-group-item-action d-flex align-items-center"
                           data-bs-toggle="tab" data-bs-target="#myDraftsContent">
                            <i class="fas fa-file-alt text-secondary me-3"></i>
                            <div class="flex-grow-1">
                                <h6 class="mb-0">我的草稿</h6>
                                <small class="text-muted">查看和编辑未发布的活动草稿</small>
                            </div>
                            <span class="badge bg-warning rounded-pill">{{ drafts_count }}</span>
                        </a>

                    </div>
                </div>
            </div>

            <!-- 标签页内容 -->
            <div class="tab-content">
                <!-- 个人主页内容 -->
                <div class="tab-pane fade show active" id="profileContent">
                    <!-- 最近参与的活动 -->
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">📅 最近参与的活动</h6>
                            <a href="#" class="btn btn-sm btn-outline-primary" data-bs-toggle="tab" data-bs-target="#myRegistrationsContent">查看全部</a>
                        </div>
                        <div class="card-body">
                            {% if recent_events %}
                            <div class="list-group list-group-flush">
                                {% for registration in recent_events %}
                                <div class="list-group-item px-0">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="bg-light rounded d-flex align-items-center justify-content-center me-3"
                                                 style="width: 60px; height: 60px;">
                                                <i class="fas fa-calendar text-muted"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">
                                                <a href="{% url 'location:activity_detail' registration.event.id %}" class="text-decoration-none">
                                                    {{ registration.event.title }}
                                                </a>
                                            </h6>
                                            <div class="d-flex text-muted small mb-1">
                                                <span class="me-3"><i class="fas fa-calendar me-1"></i>{{ registration.event.start_time|date:"Y-m-d" }}</span>
                                                <span><i class="fas fa-map-marker-alt me-1"></i>{{ registration.event.location }}</span>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <span class="badge {% if registration.event.status == 'completed' %}bg-success{% else %}bg-primary{% endif %} me-2">
                                                    {{ registration.event.get_status_display }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-4">
                                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                                <p class="text-muted">还没有参与任何活动</p>
                                <a href="{% url 'location:index' %}" class="btn btn-primary">去发现活动</a>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <!-- 最近发布的帖子 -->
                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h6 class="mb-0"><i class="fas fa-file-alt me-2"></i>最近发布的帖子</h6>
                            <a href="{% url 'location:community_posts' %}" class="btn btn-sm btn-outline-primary">查看全部</a>
                        </div>
                        <div class="card-body">
                            {% if recent_posts %}
                            {% for post in recent_posts %}
                            <div class="mb-3 pb-3 border-bottom">
                                <h6 class="mb-2">
                                    <a href="{% url 'location:post_detail' post.id %}" class="text-decoration-none">
                                        {{ post.title }}
                                    </a>
                                    <span class="badge bg-secondary ms-2">{{ post.get_post_type_display }}</span>
                                </h6>
                                <p class="text-muted small mb-2">
                                    {{ post.content|striptags|truncatechars:100 }}
                                </p>
                                <div class="d-flex justify-content-between align-items-center text-muted small">
                                    <span>{{ post.created_at|timesince }}前</span>
                                    <div>
                                        <span class="me-3"><i class="fas fa-eye me-1"></i>{{ post.views_count }}</span>
                                        <span class="me-3"><i class="fas fa-comment me-1"></i>{{ post.comments_count }}</span>
                                        <span><i class="fas fa-heart me-1"></i>{{ post.likes_count }}</span>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                            {% else %}
                            <div class="text-center py-4">
                                <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                <p class="text-muted">还没有发布过帖子</p>
                                <a href="{% url 'location:create_post' %}" class="btn btn-primary">发布帖子</a>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <!-- 积分记录 -->
                    <div class="card shadow-sm">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">🏆 最近积分记录</h6>
                            <a href="#" class="btn btn-sm btn-outline-primary" data-bs-toggle="tab" data-bs-target="#pointHistoryContent">积分明细</a>
                        </div>
                        <div class="card-body">
                            {% if recent_points %}
                            <div class="list-group list-group-flush">
                                {% for transaction in recent_points %}
                                <div class="list-group-item px-0">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="mb-1">{{ transaction.description }}</h6>
                                            <small class="text-muted">{{ transaction.created_at|date:"Y-m-d H:i" }}</small>
                                        </div>
                                        <div class="text-end">
                                            <span class="{% if transaction.transaction_type == 'earn' or transaction.transaction_type == 'refund' %}text-success{% else %}text-danger{% endif %} fw-bold">
                                                {% if transaction.transaction_type == 'earn' or transaction.transaction_type == 'refund' %}+{% else %}-{% endif %}{{ transaction.points }} 积分
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-4">
                                <i class="fas fa-coins fa-3x text-muted mb-3"></i>
                                <p class="text-muted">还没有积分记录</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- 我发起的活动内容 -->
                                <div class="tab-pane fade" id="myEventsContent">
                    <div class="card shadow-sm">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">📋 我发起的活动</h6>
                            <a href="{% url 'location:activity_create' %}" class="btn btn-sm btn-primary">
                                <i class="fas fa-plus me-1"></i>创建活动
                            </a>
                        </div>
                        <div class="card-body p-0">
                            {% if my_events_list %}
                            <div class="list-group list-group-flush">
                                {% for event in my_events_list %}
                                <div class="list-group-item">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <h6 class="mb-1">
                                                <a href="{% url 'location:activity_detail' event.id %}" class="text-decoration-none">
                                                    {{ event.title }}
                                                </a>
                                            </h6>
                                            <div class="d-flex text-muted small mb-2">
                                                <span class="me-3">
                                                    <i class="fas fa-calendar me-1"></i>{{ event.start_time|date:"Y-m-d H:i" }}
                                                </span>
                                                <span>
                                                    <i class="fas fa-map-marker-alt me-1"></i>{{ event.location }}
                                                </span>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <span class="badge {% if event.status == 'published' %}bg-success
                                                           {% elif event.status == 'draft' %}bg-secondary
                                                           {% elif event.status == 'cancelled' %}bg-danger
                                                           {% else %}bg-info{% endif %} me-2">
                                                    {{ event.get_status_display }}
                                                </span>
                                                <span class="badge bg-light text-dark">
                                                    <i class="fas fa-users me-1"></i>{{ event.current_participants }}/{{ event.max_participants }}
                                                </span>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <div class="btn-group">
                                                <a href="{% url 'location:activity_detail' event.id %}" class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-eye"></i>查看
                                                </a>
{#                                                {% if event.status == 'draft' or event.status == 'published' %}#}
{#                                                <a href="#" class="btn btn-sm btn-outline-secondary">#}
{#                                                    <i class="fas fa-edit"></i>编辑#}
{#                                                </a>#}
{#                                                {% endif %}#}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-5">
                                <i class="fas fa-calendar-plus fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">还没有创建任何活动</h5>
                                <p class="text-muted mb-3">创建您的第一个活动，邀请大家参与吧！</p>
                                <a href="{% url 'location:activity_create' %}" class="btn btn-primary">
                                    <i class="fas fa-plus me-2"></i>创建第一个活动
                                </a>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- 我报名的活动内容 -->
                <div class="tab-pane fade" id="myRegistrationsContent">
    <div class="card shadow-sm">
        <div class="card-header bg-light">
            <h6 class="mb-0">📝 我报名的活动</h6>
        </div>
        <div class="card-body p-0">
            {% if my_registrations_list %}
            <div class="list-group list-group-flush">
                {% for registration in my_registrations_list %}
                <div class="list-group-item">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-1">
                                <a href="{% url 'location:activity_detail' registration.event.id %}" class="text-decoration-none">
                                    {{ registration.event.title }}
                                </a>
                            </h6>
                            <div class="d-flex text-muted small mb-2">
                                <span class="me-3">
                                    <i class="fas fa-calendar me-1"></i>{{ registration.event.start_time|date:"Y-m-d H:i" }}
                                </span>
                                <span>
                                    <i class="fas fa-map-marker-alt me-1"></i>{{ registration.event.location }}
                                </span>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="badge {% if registration.status == 'registered' %}bg-primary
                                           {% elif registration.status == 'attended' %}bg-success
                                           {% elif registration.status == 'cancelled' %}bg-danger
                                           {% else %}bg-warning{% endif %} me-2">
                                    {{ registration.get_status_display }}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-users me-1"></i>{{ registration.event.current_participants }}/{{ registration.event.max_participants }}
                                </span>
                            </div>
                        </div>
                        <div class="col-md-4 text-end">
                            <div class="d-flex flex-column align-items-end">
                                <div class="btn-group mb-2">
                                    <a href="{% url 'location:activity_detail' registration.event.id %}" class="btn btn-sm btn-primary">
                                        <i class="fas fa-eye me-1"></i>查看详情
                                    </a>

                                    <!-- 取消报名按钮 -->
                                    {% if registration.status == 'registered' %}
                                    <form method="post" class="cancel-registration-form ms-1">
                                        {% csrf_token %}
                                        <input type="hidden" name="event_id" value="{{ registration.event.id }}">
                                        <button type="submit" class="btn btn-sm btn-outline-danger cancel-registration-btn"
                                                data-event-title="{{ registration.event.title }}">
                                            <i class="fas fa-times me-1"></i>取消报名
                                        </button>
                                    </form>
                                    {% else %}
                                    <span class="btn btn-sm btn-outline-secondary disabled">
                                        {% if registration.status == 'attended' %}
                                        <i class="fas fa-check me-1"></i>已参加
                                        {% elif registration.status == 'cancelled' %}
                                        <i class="fas fa-ban me-1"></i>已取消
                                        {% else %}
                                        <i class="fas fa-info me-1"></i>{{ registration.get_status_display }}
                                        {% endif %}
                                    </span>
                                    {% endif %}
                                </div>
                                <div class="text-muted small">
                                    <i class="fas fa-clock me-1"></i>
                                    报名时间: {{ registration.registration_time|date:"Y-m-d H:i" }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <div class="text-center py-5">
                <i class="fas fa-calendar-check fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">还没有报名任何活动</h5>
                <p class="text-muted mb-3">去发现有趣的活动并报名参与吧！</p>
                <a href="{% url 'location:activity_list' %}" class="btn btn-primary">
                    <i class="fas fa-search me-2"></i>发现活动
                </a>
            </div>
            {% endif %}
        </div>
    </div>
</div>

                <!-- 我的评价内容 -->
                <div class="tab-pane fade" id="myReviewsContent">
    <div class="card shadow-sm">
        <div class="card-header bg-light">
            <h6 class="mb-0">💬 我的评论</h6>
        </div>
        <div class="card-body p-0">
            {% if my_reviews_list %}
            <div class="list-group list-group-flush">
                {% for discussion in my_reviews_list %}
                <div class="list-group-item">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="d-flex align-items-center mb-2">
                                <h6 class="mb-0 me-3">
                                    <a href="{% url 'location:activity_detail' discussion.event.id %}" class="text-decoration-none">
                                        {{ discussion.event.title }}
                                    </a>
                                </h6>
                                {% if discussion.is_pinned %}
                                <span class="badge bg-warning ms-2">置顶</span>
                                {% endif %}
                            </div>
                            <p class="mb-2">{{ discussion.content }}</p>

                            <!-- 显示点赞数 -->
                            <div class="d-flex align-items-center text-muted small mb-2">
                                <i class="fas fa-thumbs-up me-1"></i>
                                <span class="me-3">{{ discussion.likes_count }} 点赞</span>
                                <i class="fas fa-clock me-1"></i>
                                <span>{{ discussion.created_at|date:"Y-m-d H:i" }}</span>
                            </div>

                            <!-- 如果有图片 -->
                            {% if discussion.images %}
                            <div class="review-images mb-2">
                                {% for image_url in discussion.images %}
                                <img src="{{ image_url }}" alt="评论图片"
                                     class="rounded me-2" style="width: 60px; height: 60px; object-fit: cover;">
                                {% endfor %}
                            </div>
                            {% endif %}
                        </div>
                        <div class="col-md-4 text-end">
                            <div class="btn-group">
                                <a href="{% url 'location:activity_detail' discussion.event.id %}" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-eye me-1"></i>查看活动
                                </a>
                                <button class="btn btn-sm btn-outline-danger delete-comment"
                                        data-comment-id="{{ discussion.id }}">
                                    <i class="fas fa-trash me-1"></i>删除
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <div class="text-center py-5">
                <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">还没有发表任何评论</h5>
                <p class="text-muted mb-3">去活动详情页参与讨论吧！</p>
                <a href="{% url 'location:activity_list' %}" class="btn btn-primary">
                    <i class="fas fa-search me-2"></i>去发现活动
                </a>
            </div>
            {% endif %}
        </div>
    </div>
</div>

                <!-- 积分明细内容 -->
                <div class="tab-pane fade" id="pointHistoryContent">
                    <div class="card shadow-sm">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">🏆 积分明细</h6>
                        </div>
                        <div class="card-body">
                            <!-- 积分统计 -->
                            <div class="row text-center mb-4">
                                <div class="col-4">
                                    <div class="h4 text-primary mb-1">{{ user.points }}</div>
                                    <small class="text-muted">当前积分</small>
                                </div>
                                <div class="col-4">
                                    <div class="h4 text-success mb-1">{{ total_earned|default:0 }}</div>
                                    <small class="text-muted">总获得积分</small>
                                </div>
                                <div class="col-4">
                                    <div class="h4 text-danger mb-1">{{ total_spent|default:0 }}</div>
                                    <small class="text-muted">总消费积分</small>
                                </div>
                                 <div>
                                    <a href="{% url 'location:redemption_history' %}" class="btn btn-primary">
                                        <i class="fas fa-search me-2"></i>兑换记录
                                    </a>
                                </div>
                            </div>

                            <!-- 积分记录 -->
                            <h6 class="mb-3">积分记录</h6>
                            {% if transactions %}
                            <div class="list-group list-group-flush">
                                {% for transaction in transactions %}
                                <div class="list-group-item px-0">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="mb-1">{{ transaction.description }}</h6>
                                            <small class="text-muted">{{ transaction.created_at|date:"Y-m-d H:i" }}</small>
                                        </div>
                                        <div class="text-end">
                                            <span class="{% if transaction.transaction_type == 'earn' or transaction.transaction_type == 'refund' %}text-success{% else %}text-danger{% endif %} fw-bold">
                                                {% if transaction.transaction_type == 'earn' or transaction.transaction_type == 'refund' %}+{% else %}-{% endif %}{{ transaction.points }} 积分
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-4">
                                <i class="fas fa-coins fa-3x text-muted mb-3"></i>
                                <p class="text-muted">还没有积分记录</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- 隐私设置内容 -->
                <div class="tab-pane fade" id="privacySettingsContent">
    <div class="card shadow-sm">
        <div class="card-header bg-light">
            <h6 class="mb-0">🔒 隐私设置</h6>
        </div>
        <div class="card-body">
            <form method="post" action="{% url 'customer:privacy_settings' %}">
                {% csrf_token %}

                <div class="mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="show_email"
                               id="showEmail" {% if user.show_email %}checked{% endif %}>
                        <label class="form-check-label" for="showEmail">
                            公开邮箱地址
                        </label>
                    </div>
                    <small class="form-text text-muted">其他用户可以看到您的邮箱</small>
                </div>

                <div class="mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="show_phone"
                               id="showPhone" {% if user.show_phone %}checked{% endif %}>
                        <label class="form-check-label" for="showPhone">
                            公开手机号码
                        </label>
                    </div>
                    <small class="form-text text-muted">其他用户可以看到您的手机号</small>
                </div>

                <div class="mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="show_location"
                               id="showLocation" {% if user.show_location %}checked{% endif %}>
                        <label class="form-check-label" for="showLocation">
                            公开所在地
                        </label>
                    </div>
                    <small class="form-text text-muted">在个人资料中显示您的位置信息</small>
                </div>

                <button type="submit" class="btn btn-primary">保存设置</button>
            </form>
        </div>
    </div>
</div>

                <!-- 我的草稿内容 -->
                <div class="tab-pane fade" id="myDraftsContent" role="tabpanel">
                <div class="card shadow-sm">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">📝 我的草稿</h6>
                        <span class="badge bg-warning">{{ drafts_count }}</span>
                    </div>
                    <div class="card-body p-0">
                        {% if drafts %}
                        <div class="list-group list-group-flush">
                            {% for draft in drafts %}
                            <div class="list-group-item">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1 text-dark">{{ draft.title|default:"未命名活动" }}</h6>
                                        <div class="d-flex text-muted small mb-2">
                                            {% if draft.start_time %}
                                            <span class="me-3">
                                                <i class="fas fa-calendar me-1"></i>{{ draft.start_time|date:"Y-m-d H:i" }}
                                            </span>
                                            {% endif %}
                                            {% if draft.location %}
                                            <span>
                                                <i class="fas fa-map-marker-alt me-1"></i>{{ draft.location|truncatechars:20 }}
                                            </span>
                                            {% endif %}
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <span class="badge bg-warning me-2">草稿</span>
                                            <span class="badge bg-light text-dark me-2">
                                                <i class="fas fa-users me-1"></i>
                                                {% if draft.max_participants %}
                                                {{ draft.current_participants|default:0 }}/{{ draft.max_participants }}
                                                {% else %}
                                                人数未设置
                                                {% endif %}
                                            </span>
                                            <span class="text-muted small">
                                                <i class="fas fa-clock me-1"></i>
                                                创建于: {{ draft.created_at|date:"Y-m-d H:i" }}
                                            </span>
                                        </div>

                                        <!-- 显示缺失的必填字段 -->
                                        {% if not draft.title or not draft.description or not draft.start_time %}
                                        <div class="mt-2">
                                            <small class="text-danger">
                                                <i class="fas fa-exclamation-triangle me-1"></i>
                                                缺失信息:
                                                {% if not draft.title %}标题{% endif %}
                                                {% if not draft.description %}描述{% endif %}
                                                {% if not draft.start_time %}开始时间{% endif %}
                                            </small>
                                        </div>
                                        {% endif %}
                                    </div>
                                    <div class="btn-group ms-3 flex-shrink-0" role="group">
                                        <!-- 编辑 -->
                                        <a href="{% url 'location:activity_create' %}?draft_id={{ draft.id }}"
                                           class="btn btn-outline-primary btn-sm">
                                            <i class="fas fa-edit"></i> 编辑
                                        </a>

                                        <!-- 删除按钮 -->
                                        <button type="button"
                                                class="btn btn-outline-danger btn-sm delete-draft-btn"
                                                data-draft-id="{{ draft.id }}"
                                                data-draft-title="{{ draft.title|default:'未命名活动' }}">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <div class="text-center py-5">
                            <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">还没有任何草稿</h5>
                            <p class="text-muted mb-3">创建活动时可以选择保存为草稿</p>
                            <a href="{% url 'location:activity_create' %}" class="btn btn-primary">
                                <i class="fas fa-plus me-2"></i> 创建新活动
                            </a>
                        </div>
                        {% endif %}
                    </div>
                </div>
</div>

</div>
            </div>
        </div>
    </div>
</div>

<!-- 编辑头像模态框 -->
<div class="modal fade" id="editAvatarModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">更换头像</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="{% url 'customer:update_profile' %}" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="modal-body text-center">
                    <div class="mb-3">
                        <img id="avatarPreview" src="{{ user.avatar_url|default:'/static/images/default-avatar.jpg' }}"
                             alt="当前头像" class="rounded-circle mb-3" width="120" height="120" style="object-fit: cover;">
                    </div>
                    <div class="d-grid gap-2">
                        <input type="file" name="avatar" id="avatarInput" accept="image/*" class="d-none" onchange="previewImage(this)">
                        <label for="avatarInput" class="btn btn-primary">
                            <i class="fas fa-camera me-2"></i>上传新头像
                        </label>
                        <button type="submit" class="btn btn-success" id="saveAvatarBtn" style="display: none;">
                            <i class="fas fa-save me-2"></i>保存头像
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑资料模态框 -->
<div class="modal fade" id="editProfileModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑个人资料</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="{% url 'customer:update_profile' %}">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="row g-3">
                        <!-- 原有的用户基本信息 -->
                        <div class="col-md-6">
                            <label for="editUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="editUsername" value="{{ user.username }}" readonly>
                            <small class="form-text text-muted">用户名不可修改</small>
                        </div>
                        <div class="col-md-6">
                            <label for="editEmail" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="editEmail" value="{{ user.email }}" readonly>
                            <small class="form-text text-muted">邮箱不可修改</small>
                        </div>
                        <div class="col-md-6">
                            <label for="editPhone" class="form-label">手机号</label>
                            <input type="tel" class="form-control" id="editPhone" name="phone" value="{{ user.phone|default:'' }}">
                        </div>
                        <div class="col-md-6">
                            <label for="editLocation" class="form-label">所在地</label>
                            <input type="text" class="form-control" id="editLocation" name="location" value="{{ user.location|default:'' }}">
                        </div>
                        <div class="col-12">
                            <label for="editBio" class="form-label">个人简介</label>
                            <textarea class="form-control" id="editBio" name="bio" rows="3"
                                      placeholder="介绍一下自己...">{{ user.bio|default:'' }}</textarea>
                        </div>
                        <div class="col-12">
                            <label for="editInterests" class="form-label">兴趣标签</label>
                            <input type="text" class="form-control" id="editInterests" name="interests"
                                   value="{{ user.interests|default:'' }}" placeholder="例如：篮球 阅读 音乐 旅行">
                            <small class="form-text text-muted">多个兴趣请用空格分隔</small>
                        </div>

                        <!-- 新增的 UserProfile 字段 -->
                        <div class="col-md-6">
                            <label for="editGender" class="form-label">性别</label>
                            <select class="form-select" id="editGender" name="gender">
                                <option value="">请选择性别</option>
                                <option value="male" {% if user.profile.gender == 'male' %}selected{% endif %}>男</option>
                                <option value="female" {% if user.profile.gender == 'female' %}selected{% endif %}>女</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="editBirthDate" class="form-label">生日</label>
                            <input type="date" class="form-control" id="editBirthDate" name="birth_date"
                                   value="{% if user.profile.birth_date %}{{ user.profile.birth_date|date:'Y-m-d' }}{% endif %}">
                        </div>
                        <div class="col-md-6">
                            <label for="editOccupation" class="form-label">职业</label>
                            <input type="text" class="form-control" id="editOccupation" name="occupation"
                                   value="{{ user.profile.occupation|default:'' }}" placeholder="请输入您的职业">
                        </div>
                        <div class="col-md-6">
                            <label for="editWechatId" class="form-label">微信号</label>
                            <input type="text" class="form-control" id="editWechatId" name="wechat_id"
                                   value="{{ user.profile.wechat_id|default:'' }}" placeholder="请输入您的微信号">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// 头像预览功能
function previewImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatarPreview').src = e.target.result;
            document.getElementById('saveAvatarBtn').style.display = 'block';
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// 删除草稿功能
function initDraftDeletion() {
    const deleteButtons = document.querySelectorAll('.delete-draft-btn');

    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            const draftId = this.getAttribute('data-draft-id');
            const draftTitle = this.getAttribute('data-draft-title');

            if (!confirm(`确定要删除草稿 "${draftTitle}" 吗？此操作不可恢复。`)) {
                return;
            }

            // 显示加载状态
            const originalHTML = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            this.disabled = true;

            // 发送删除请求
            const deleteUrl = `/customer/delete-draft/${draftId}/`;

            fetch(deleteUrl, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showAlert('✅ ' + data.message, 'success');

                    // 平滑移除草稿项
                    const draftItem = this.closest('.list-group-item');
                    if (draftItem) {
                        draftItem.style.transition = 'all 0.3s ease';
                        draftItem.style.opacity = '0';
                        draftItem.style.transform = 'translateX(-100%)';

                        setTimeout(() => {
                            draftItem.remove();

                            // 更新草稿数量
                            updateDraftsCount(-1);

                            // 检查是否还有草稿，如果没有则显示空状态
                            const remainingDrafts = document.querySelectorAll('#myDraftsContent .list-group-item');
                            if (remainingDrafts.length === 0) {
                                setTimeout(() => {
                                    location.reload(); // 重新加载以显示空状态
                                }, 500);
                            }
                        }, 300);
                    }
                } else {
                    showAlert('❌ ' + (data.message || '删除失败'), 'error');
                    this.innerHTML = originalHTML;
                    this.disabled = false;
                }
            })
            .catch(error => {
                console.error('删除草稿失败:', error);
                showAlert('❌ 网络错误，请重试', 'error');
                this.innerHTML = originalHTML;
                this.disabled = false;
            });
        });
    });
}

// 更新草稿数量显示
function updateDraftsCount(change) {
    const draftsBadge = document.querySelector('a[data-bs-target="#myDraftsContent"] .badge');
    if (draftsBadge) {
        let currentCount = parseInt(draftsBadge.textContent) || 0;
        currentCount += change;
        if (currentCount <= 0) {
            draftsBadge.style.display = 'none';
        } else {
            draftsBadge.textContent = currentCount;
            draftsBadge.style.display = 'inline-block';
        }
    }
}

// 绑定草稿相关功能
function bindDraftFunctions() {
    initDraftDeletion(); // 只保留删除功能
}

// 阻止标签页切换时的URL变化
document.addEventListener('DOMContentLoaded', function() {
    // 标签页切换 - 阻止URL更新
    const tabLinks = document.querySelectorAll('.list-group-item[data-bs-toggle="tab"]');
    tabLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            // 移除所有激活状态
            tabLinks.forEach(l => l.classList.remove('active'));
            // 添加当前激活状态
            this.classList.add('active');

            // 不更新URL，保持当前页面
        });
    });

    // 头像上传成功后的处理
    var avatarForm = document.querySelector('#editAvatarModal form');
    if (avatarForm) {
        avatarForm.addEventListener('submit', function(e) {
            e.preventDefault();
            var formData = new FormData(this);

            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                }
            })
            .then(response => {
                if (response.ok) {
                    return response;
                }
                throw new Error('Network response was not ok.');
            })
            .then(() => {
                // 显示成功消息
                showAlert('头像更新成功！', 'success');
                // 关闭模态框
                var modal = bootstrap.Modal.getInstance(document.getElementById('editAvatarModal'));
                modal.hide();
                // 刷新页面以更新所有头像显示
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('头像更新失败', 'error');
            });
        });
    }

    // 编辑资料表单提交处理
    var profileForm = document.querySelector('#editProfileModal form');
    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            var formData = new FormData(this);

            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                }
            })
            .then(response => {
                if (response.ok) {
                    return response;
                }
                throw new Error('Network response was not ok.');
            })
            .then(() => {
                // 显示成功消息
                showAlert('个人资料更新成功！', 'success');
                // 关闭模态框
                var modal = bootstrap.Modal.getInstance(document.getElementById('editProfileModal'));
                modal.hide();
                // 刷新页面以更新所有数据
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('个人资料更新失败', 'error');
            });
        });
    }

    // 隐私设置表单提交处理
    var privacyForm = document.querySelector('#privacySettingsContent form');
    if (privacyForm) {
        privacyForm.addEventListener('submit', function(e) {
            e.preventDefault();
            var formData = new FormData(this);

            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                }
            })
            .then(response => {
                if (response.ok) {
                    return response;
                }
                throw new Error('Network response was not ok.');
            })
            .then(() => {
                // 显示成功消息
                showAlert('隐私设置更新成功！', 'success');
                // 刷新页面以更新所有数据
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('隐私设置更新失败', 'error');
            });
        });
    }

    // 活动取消报名处理
    function bindCancelForms() {
        const cancelForms = document.querySelectorAll('.cancel-registration-form');
        console.log(`找到 ${cancelForms.length} 个取消报名表单`);

        cancelForms.forEach(form => {
            // 移除之前的事件监听器
            form.replaceWith(form.cloneNode(true));
        });

        // 重新获取元素并绑定事件
        const newCancelForms = document.querySelectorAll('.cancel-registration-form');
        newCancelForms.forEach(form => {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                e.stopPropagation();

                const eventTitle = this.querySelector('button').getAttribute('data-event-title') || '该活动';
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.innerHTML;

                if (!confirm(`确定要取消 "${eventTitle}" 的报名吗？`)) {
                    return;
                }

                // 显示加载状态
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>取消中...';
                submitBtn.disabled = true;

                const formData = new FormData(this);

                fetch("{% url 'customer:cancel_registration' %}", {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRFToken': getCsrfToken(),
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showAlert('✅ ' + data.message, 'success');

                        // 平滑移除对应的活动条目
                        const listItem = form.closest('.list-group-item');
                        if (listItem) {
                            listItem.style.transition = 'all 0.3s ease';
                            listItem.style.opacity = '0';
                            listItem.style.transform = 'translateX(-100%)';

                            setTimeout(() => {
                                listItem.remove();

                                // 检查是否还有活动，如果没有显示空状态
                                const remainingItems = document.querySelectorAll('#myRegistrationsContent .list-group-item');
                                if (remainingItems.length === 0) {
                                    setTimeout(() => {
                                        location.reload();
                                    }, 500);
                                }
                            }, 300);
                        } else {
                            setTimeout(() => {
                                location.reload();
                            }, 1500);
                        }
                    } else {
                        showAlert('❌ ' + (data.message || '取消报名失败'), 'error');
                        submitBtn.innerHTML = originalText;
                        submitBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('取消报名请求失败:', error);
                    showAlert('❌ 网络错误，请重试', 'error');
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                });
            });
        });
    }

    // 删除评论处理
    const deleteButtons = document.querySelectorAll('.delete-comment');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const commentId = this.getAttribute('data-comment-id');

            if (!confirm('确定要删除这条评论吗？')) {
                return;
            }

            // 显示加载状态
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>删除中...';
            this.disabled = true;

            fetch(`/customer/profile/delete-comment/${commentId}/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showAlert('评论删除成功！', 'success');
                    // 平滑移除评论元素
                    const commentElement = this.closest('.list-group-item');
                    if (commentElement) {
                        commentElement.style.transition = 'all 0.3s ease';
                        commentElement.style.opacity = '0';
                        commentElement.style.height = commentElement.offsetHeight + 'px';

                        setTimeout(() => {
                            commentElement.style.height = '0';
                            commentElement.style.padding = '0';
                            commentElement.style.margin = '0';
                            commentElement.style.overflow = 'hidden';
                        }, 10);

                        setTimeout(() => {
                            commentElement.remove();

                            // 检查是否还有评论，如果没有则显示空状态
                            const remainingComments = document.querySelectorAll('#myReviewsContent .list-group-item');
                            if (remainingComments.length === 0) {
                                // 重新加载页面以显示空状态
                                setTimeout(() => {
                                    location.reload();
                                }, 500);
                            }
                        }, 300);
                    }
                } else {
                    showAlert('删除失败: ' + data.message, 'error');
                    // 恢复按钮状态
                    this.innerHTML = originalText;
                    this.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('删除失败，请检查网络连接', 'error');
                // 恢复按钮状态
                this.innerHTML = originalText;
                this.disabled = false;
            });
        });
    });

    // 初始绑定各种功能
    bindCancelForms();
    bindDraftFunctions(); // 绑定草稿相关功能

    // 标签页切换时重新绑定
    const menuLinks = document.querySelectorAll('.list-group-item[data-bs-toggle="tab"]');
    menuLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            setTimeout(() => {
                bindCancelForms();
                bindDraftFunctions(); // 重新绑定草稿相关功能
            }, 300);
        });
    });

    // 标签页切换功能
    var triggerTabList = [].slice.call(document.querySelectorAll('a[data-bs-toggle="tab"]'))
    triggerTabList.forEach(function (triggerEl) {
        var tabTrigger = new bootstrap.Tab(triggerEl)
        triggerEl.addEventListener('click', function (event) {
            event.preventDefault()
            tabTrigger.show()
        })
    });
});

// 显示消息提示
function showAlert(message, type) {
    // 移除现有消息
    const existingAlerts = document.querySelectorAll('.alert');
    existingAlerts.forEach(alert => alert.remove());

    // 创建消息元素
    const alertEl = document.createElement('div');
    alertEl.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
    alertEl.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertEl.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alertEl);

    // 5秒后自动消失
    setTimeout(() => {
        if (alertEl.parentNode) {
            alertEl.remove();
        }
    }, 5000);
}

// 显示消息提示（兼容旧代码）
function showMessage(message, type) {
    showAlert(message, type);
}

// 工具函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 获取CSRF token的函数
function getCsrfToken() {
    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
    return csrfToken ? csrfToken.value : '';
}
</script>
{% endblock %}